﻿using System;
using System.Web.Mvc;
using Actya.Web.Infrastructure;
using Actya.Web.ViewModels.Admin;

namespace Actya.Web.ModelBinders
{
    public class ContentModelBinder : DefaultModelBinder
    {
		public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			var newBindingContext = new ModelBindingContext(bindingContext);
			newBindingContext.ModelName = bindingContext.ModelName;
			var contentModelTypeString = controllerContext.HttpContext.Request.Form["ContentModelType"];
			if (! String.IsNullOrEmpty(contentModelTypeString))
			{
				var contentTypeType = Type.GetType(contentModelTypeString);
				var item = Activator.CreateInstance(contentTypeType);
				Func<object> modelAccessor = () => item;
				newBindingContext.ModelMetadata = new ModelMetadata(new DataAnnotationsModelMetadataProvider(),
					bindingContext.ModelMetadata.ContainerType, modelAccessor, item.GetType(), bindingContext.ModelName);

				return base.BindModel(controllerContext, newBindingContext);
			}
			return base.BindModel(controllerContext, bindingContext);
		}
    }
}
